package org.huamoxi.config;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import org.huamoxi.constant.RedisConstants;
import org.huamoxi.constant.TokenConstants;
import org.huamoxi.result.Result;
import org.huamoxi.utils.CacheUtils;
import org.huamoxi.utils.JwtUtils;
import org.huamoxi.utils.ResultUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    static String NO_AUTH_MESSAGE = "未登录";

    String[] whites = {"/auth/login", "/auth/logout", "/"};

    @Resource
    CacheUtils cacheUtils;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse resp = exchange.getResponse();
        ServerHttpRequest req = exchange.getRequest();

        String url = req.getURI().getPath();
        System.out.println("url-->");
        System.out.println(url);
        // 跳过不需要验证的路径
        for (String str: whites) {
            if (url.equalsIgnoreCase(str)) {
                return chain.filter(exchange);
            }
        }

        // 获取参数中的 authorization 参数
        String tokenStr = req.getHeaders().getFirst(TokenConstants.AUTHENTICATION);
        String token = "";
        if (StrUtil.isNotBlank(tokenStr)) {
            token = tokenStr.split(TokenConstants.PREFIX)[1];
        }

        // 判断 authorization 是否命中
        try {
            System.out.println("token是--->");
            System.out.println(token);

            Claims claims = JwtUtils.verifyToken(token);
            System.out.println(claims);

//            req.mutate().header(TokenConstants.AUTHENTICATION, token);

            // 验证未报错, 放行
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();

            Result fail = ResultUtils.fail(NO_AUTH_MESSAGE);
            String msg = JSONUtil.toJsonStr(fail);

            // 设置状态码 并 拦截请求
            resp.setStatusCode(HttpStatus.UNAUTHORIZED);
            return resp.writeWith(Mono.just(resp.bufferFactory().wrap(msg.getBytes())));
        }
    }

    // 设置顺序 优先执行此过滤器
    @Override
    public int getOrder() {
        return -1;
    }
}
